package com.luoye.lj.platform.controller;

import com.luoye.lj.util.mvc.annotation.OperateLog;
import com.luoye.lj.util.mvc.data.SimpleResponseBody;
import com.luoye.lj.util.mvc.log.DefaultDescriptionGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

/*
 * Created with IntelliJ IDEA.
 * User:
 * Date:
 * Time:
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("/system/file/upload")
public class FileUploadController {
    private Logger logger = LoggerFactory.getLogger(FileUploadController.class);

    @Value("${file.save.dir}")
    String fileSaveDir;

    @RequestMapping(value = "/image",method = RequestMethod.POST)
    @ResponseBody
    @OperateLog(value = "图片上传",descriptionGenerator = DefaultDescriptionGenerator.class)
    public SimpleResponseBody uploadPdf(HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "file", required = false) MultipartFile file){
        SimpleResponseBody srb = new SimpleResponseBody();
        String fileName=null;
        String saveFilePath=null;
        String saveFileName =null;
        if(file!=null&&!file.isEmpty()) {
            fileName = file.getOriginalFilename();
            String extendName = fileName.substring(fileName.lastIndexOf("."));
            String imageExtendNames=".BMP,.JPG,.JPEG,.PNG,.GIF,";
            //检查文件格式是否正确
            if (!imageExtendNames.contains(extendName.toUpperCase() + ",")) {
                srb.setOk(false);
                srb.setMsg("上传文件格式不支持!");
                return srb;
            }
           //String currentTime = new Date().getTime() + "";
            String uuid = UUID.randomUUID().toString();
            saveFileName = uuid + "_img";// extendName;
            String saveFileDir = fileSaveDir;
            File fileDir = new File(saveFileDir);
            if (!fileDir.exists() || !fileDir.isDirectory()) {
                fileDir.mkdirs();
            }
            saveFilePath = saveFileDir + "/" + saveFileName;
        }
        //logger.debug(classify+","+outline+","+id+",fileName->"+fileName+",formName->"+formName+",extendName->"+extendName+",currentTime->"+currentTime+",uuid->"+uuid+",saveFileName->"+saveFileName);
        logger.debug("saveFilePath->"+saveFilePath);

        try {
            if(fileName==null){
                srb.setMsg("请选择上传的文件");
                srb.setOk(false);
                return srb;
            }
            file.transferTo(new File(saveFilePath));
            String host = request.getRequestURL().substring(0, request.getRequestURL().indexOf(request.getContextPath()));
            if(StringUtils.isEmpty(request.getContextPath())){
                host =request.getRequestURL().substring(0, request.getRequestURL().indexOf("/",request.getRequestURL().indexOf("//")+2));
            }
            logger.info("host->" + host);
            String url = host + request.getContextPath() + "/system/file/view/image/" + saveFileName;
            srb.setEntity(url);
            srb.setMsg("保存成功");
            srb.setOk(true);
        } catch (IOException e) {
            logger.warn(e.getMessage(),e);
            srb.setOk(false);
            srb.setMsg("保存文件到服务器失败！");
        }
        return srb;
    }
}
